﻿using UnityEngine;
using UnityEngine.Extension;
using System.Collections;
using UnityEngine.UI;
using System.Extension;
using System;
[AddComponentMenu("UI/SubjectiveText")]
public class SubjectiveText : Text
{
    [SerializeField]
    ControlSubject m_subject = new ControlSubject(false);
    public ControlSubject subject { get { return m_subject; } }

    public string m_key;
    protected override void Start()
    {
        base.Start();
        AssignText();
    }

    private void AssignText()
    {
        if (subject.hasContent)
        {
            string value = subject.value.ToString();
            if (value.isNotNull())
            {
                if (subject.localize)  AssignLocalizedText(value);
                else  text = value;
                AssignFontAndMaterial();
            }
        }
        else if (m_key.isNotEmpty())  AssignLocalizedText(m_key);
    }

    private void AssignLocalizedText(string key)
    {
        string localizedText = Localizer.GetText(key);
        if (localizedText.isNotEmpty())
            text = localizedText;
        AssignFontAndMaterial();
    }

    private void AssignFontAndMaterial()
    {
        if (Localizer.font.isNotNone())
            font = Localizer.font;
        if (Localizer.fontMaterial.isNotNone())
            material = Localizer.fontMaterial;
    }

    void LateUpdate()
    {
        if (subject.hasUpdate)
            AssignText();
    }

#if UNITY_EDITOR

    protected override void OnValidate()
    {
        base.OnValidate();
        AssignText();
    }
#endif
}
